package cn.virens.common.mybatis.fastjson;

import cn.virens.common.mybatis.entity.BaseEnum;
import cn.virens.common.util.exception.APIException;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.writer.ObjectWriter;

import java.lang.reflect.Type;
import java.util.Objects;
import java.util.function.BiFunction;

public final class BaseEnumSerializer implements ObjectWriter<Object>, BiFunction<String, Object, Object> {
    public final static BaseEnumSerializer instance = new BaseEnumSerializer();

    private BaseEnumSerializer() {
    }

    @Override
    public void write(JSONWriter jsonWriter, Object fieldObject, Object fieldName, Type fieldType, long features) {
        if (jsonWriter != null && fieldObject != null && fieldObject instanceof BaseEnum<?> value) {
            jsonWriter.writeString(apply(Objects.toString(fieldName), value).toString());

            return;
        }

        jsonWriter.writeNull();
    }

    @Override
    public Object apply(String name, Object object) throws APIException {
        if (object instanceof BaseEnum<?> value) {
            return value.getKey();
        } else {
            return object;
        }
    }

}
